﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DAL;
using Utils.ControlToLoad;
using Utils.Exceptions;
using Utils.Web;
using System.Collections.Generic;

namespace Prototype1
{
    public partial class FormExpenseType : PageWithDDlAndId
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.DataBind();
                this.ControlId = Guid.NewGuid();
            }
            else
            {
                //Control c = Page.LoadControl("MetaEditControls\\ControlTemplateDislocations.ascx");
                //this.PlaceHolder1.Controls.Add(c);

                //if (!string.IsNullOrEmpty(this.SelectedControlName))
                //{
                //    Control c = Page.LoadControl(this.SelectedControlName);
                //    this.PlaceHolder1.Controls.Add(c);
                //    ((IControlToLoadW)c).Bind(this.ControlId);
                //}

                //tenho que carregar todos os controlos
                using (DataAccessDataContext dc = new DataAccessDataContext())
                {
                    var result = from t in dc.Templates
                                 select t;
                    IEnumerator templates = result.GetEnumerator();
                    while (templates.MoveNext())
                    {
                        String controlName = ((Template)(templates.Current)).MetaEditControl;
                        Control c = Page.LoadControl("MetaEditControls\\" + controlName);
                        ((IControlToLoadW)c).Bind(this.ControlId);
                        this.PlaceHolder1.Controls.Add(c);
                    }

                    //var query = from exp in dc.ExpenseLines
                    //            select exp;
                    //query.GetEnumerator();
                }
            }
        }

        //aqui só deixo ficar aquele que está selecionado. Se não estiver nenhum selecionado n fica nenhum.
        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);
            if (string.IsNullOrEmpty(this.SelectedControlName))
            {
                this.PlaceHolder1.Controls.Clear();
                return;
            }
            //mal feito, devia ser carregado o tipo a partir da string para evitar este LoadControl
            Type t = Page.LoadControl(this.SelectedControlName).GetType();
            
            //se o controlo não for o selecionado é removido
            IEnumerator phControls = this.PlaceHolder1.Controls.GetEnumerator();
            List<object> toRemove = new List<object>();
            while (phControls.MoveNext())
            {
                if (t != phControls.Current.GetType())
                    toRemove.Add(phControls.Current);
                    
            }
            foreach (object o in toRemove)
            {
                this.PlaceHolder1.Controls.Remove((Control)o);
            }
        }

        //rever isto
        public override void DataBind()
        {
            DataAccessDataContext dc = new DataAccessDataContext();

            var result = from t in dc.Templates
                         select t;
            ddl_Template.DataSource = result;
            IEnumerable a = result.AsEnumerable();
            //ddl_Template.i new String[]{"Benfica", "SLB", "Sport Lisboa e Benfica"};

            base.DataBind();
            dc.Dispose();
        }

        //aqui passa a ser feito save só daquele que está selecionado
        protected void bt_Submit_Click(object sender, EventArgs e)
        {
            //No futuro devia ter validators

            String name = tb_Name.Text;
            String description = tb_Description.Text;
            bool requiresJust = cb_RequiresJust.Checked;
            String template = ddl_Template.SelectedValue;

            ExpenseType expenseType = new ExpenseType();
            expenseType.Name = name;
            expenseType.Description = description;
            expenseType.RequiresJust = requiresJust;
            expenseType.Type = template;
            expenseType.Id = this.ControlId;

            using (DataAccessDataContext dc = new DataAccessDataContext())
            {
                dc.ExpenseTypes.InsertOnSubmit(expenseType);
                dc.SubmitChanges();
            }
            //rever esta linha de código
            //((IControlToLoad)(this.PlaceHolder1.Controls.GetEnumerator().Current)).Save();
            if (string.IsNullOrEmpty(this.SelectedControlName))
            {
                return;
            }
            Type t = Page.LoadControl(this.SelectedControlName).GetType();
            IEnumerator phControls = this.PlaceHolder1.Controls.GetEnumerator();
            while (phControls.MoveNext())
            {
                if (t == phControls.Current.GetType())
                    ((IControlToLoadW)phControls.Current).Save();
            }
        }

        protected void ddl_Template_SelectedIndexChanged(object sender, EventArgs e)
        {
            String template = ddl_Template.SelectedValue;
            using (DataAccessDataContext dc = new DataAccessDataContext())
            {
                var query = from t in dc.Templates
                            where t.Name.Equals(template)
                            select t;
                Template temp = query.Single<Template>();

                this.SelectedControlName = "MetaEditControls\\" + temp.MetaEditControl;
                //Control c = Page.LoadControl(this.SelectedControlName);
                //this.PlaceHolder1.Controls.Clear();
                //this.PlaceHolder1.Controls.Add(c);
                //((IControlToLoadW)c).Bind(this.ControlId);
            }
        }
    }
}
